import java.util.ArrayList;
import java.util.List;

public class BookJsonHelper {
	/**
	 * 
	 * @param book
	 *            Book对象
	 * @return 传入book对象，返回一个json格式字符串
	 */
	public static String toJSON(Book book) {
		return String.format(
				"{\"id\":\"%d\",\"title\":\"%s\",\"price\":\"%.2f\"}",
				book.getId(), book.getTitle(), book.getPrice());
	}

	public static Book toBook(String jsonBook) {
		String[] strings = jsonBook.substring(2, jsonBook.length() - 2).split(
				"\",\"");
		int index;
		if (strings.length == 3) {
			for (int i = 0; i < strings.length; i++) {
				index = strings[i].lastIndexOf('"');
				strings[i] = strings[i].substring(index + 1);
			}
			return new Book(Integer.parseInt(strings[0]), strings[1],
					Double.parseDouble(strings[2]));
		} else {
			return null;
		}
	}

	public static String toJSON(List<Book> list) {
		StringBuilder string = new StringBuilder("[");
		for (int i = 0; i < list.size(); i++) {
			string = string.append(toJSON(list.get(i)) + ",");
		}
		return string.replace(string.length() - 1, string.length(), "]")
				.toString();
	}

	// TODO 有错误,待测试,修改
	public static List<Book> toBookList(String bookJsonList) {
		String[] strings = bookJsonList.substring(1, bookJsonList.length() - 1)
				.split("},{");
		List<Book> list = new ArrayList<Book>();
		for (int i = 0; i < strings.length; i++) {
			list.add(toBook(strings[i]));
		}
		return list;
	}
}
